package com.paw.security.jwt.config;

import com.paw.security.jwt.filter.TokenAuthenticationFilter;
import com.paw.security.jwt.filter.TokenLoginFilter;
import com.paw.security.jwt.filter.UnauthorizedEntryPoint;
import com.paw.security.jwt.service.DefaultUserDetailService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.builders.WebSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;

/**
 * @author lvzihai
 * @date 2021/7/13
 **/
@EnableGlobalMethodSecurity(prePostEnabled = true,securedEnabled=true)
@Configuration
@ConditionalOnProperty(prefix = "security",name = "type",matchIfMissing = true,havingValue = "web")
@EnableWebSecurity
public class WebSecurityConfiguration extends WebSecurityConfigurerAdapter {

  @Autowired
  private DefaultUserDetailService userDetailService;

  @Override
  protected void configure(HttpSecurity http) throws Exception {
    http.exceptionHandling()
        //未授权处理
        .authenticationEntryPoint(new UnauthorizedEntryPoint())
        .and().authorizeRequests()
        .anyRequest().authenticated()
        .and().csrf().disable()
        .logout().logoutUrl("/logout")
        .and()
        //.addLogoutHandler(new TokenLogoutHandler(tokenManager))
        .addFilter(new TokenLoginFilter(authenticationManager()))
        .addFilter(new TokenAuthenticationFilter(authenticationManager())).httpBasic();

  }

  @Autowired
  public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
    auth.userDetailsService(userDetailService)
        .passwordEncoder(passwordEncoder());

  }

  @Override
  public void configure(WebSecurity web) throws Exception {
    web.ignoring().antMatchers("/pub/**");
  }

  @Bean
  @ConditionalOnMissingBean
  public PasswordEncoder passwordEncoder(){
    return new BCryptPasswordEncoder();
  }


}